package concurrency.chapter9;

import java.util.stream.Stream;

public class DifferenceOfWaitAndSleep {
    private static final Object LOCK = new Object();

    public static void main(String[] args) {
        //m1();
        //m2();
        Stream.of("T1","T2").forEach(name->{
            new Thread(name){
                @Override
                public void run() {
                    //m1();
                    m2();
                }
            }.start();
        });
    }

    public static void m1() {
        synchronized (LOCK) {
            try {
                System.out.println("The Thread "+Thread.currentThread().getName()+" enter.");
                Thread.sleep(5_000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void m2() {
        synchronized (LOCK) {
            try {
                System.out.println("The Thread "+Thread.currentThread().getName()+" enter.");

                //需要有个monitor否则抛IllegalMonitorStateException
                LOCK.wait(5_000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
